package dhome;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.io.ObjectOutputStream;
import java.lang.reflect.Method;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Date;
import java.util.Vector;

//service:jmx:rmi:///jndi/rmi://localhost:1099/jmxrmi

public class Main {
	public static boolean keeprunning = true;
	
	static {
		String home = System.getProperty("user.dir");
		if (System.getProperty("DH_HOME") == null) {
			if (home.endsWith(File.separator + "bin"))
				home = home.substring(0, home.length() - 4);
			System.setProperty("DH_HOME", home);
		}		
	}

	@SuppressWarnings("unchecked")
	public static void main(String[] args) {
		System.out.println("HOME="+ System.getProperty("DH_HOME"));
		if(args!=null&&args.length>0){
			if("md5sum".equalsIgnoreCase(args[0]))
				md5sum(args[1]);
		}else{
			while(true){
				System.out.println("dhome start "+ new Date());
				try {
					Vector<URL> v = search_folder(new File(System.getProperty("DH_HOME") + "/lib"));
					ClassLoader urlClassLoader=null;
					if(v!=null){
						URL[] urls = new URL[v.size()];
						v.toArray(urls);
						urlClassLoader = new URLClassLoader(urls,
								ClassLoader.getSystemClassLoader());
			
						Thread.currentThread().setContextClassLoader(urlClassLoader);
					}else
						urlClassLoader=ClassLoader.getSystemClassLoader();
					
					Class cls = urlClassLoader
							.loadClass("dhome.Application");
					cls.newInstance();
					
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	public static void md5sum(String file) {
		System.out.println(Host.exec0("md5sum "+file));
	}
	
	public static void upgrade() {
		String home=System.getProperty("DH_HOME");		
		File tmp=new File(home+"/tmp");
		if(!tmp.exists())
			tmp.mkdir();
		if(tmp.list().length<2)
			return;
		
		Host.exec0("cp -Af "+home+"/tmp/** " + home+"/");
		
	}
	
	public static void backup() {
		Host.exec0("rm -rf /backup");						
		File tmp=new File("/backup");
		tmp.mkdir();
		
		String home=System.getProperty("DH_HOME");		
		Host.exec0("cp -Af "+home+"/** /backup ");
	}
	
	public static void rollback() {
		String home=System.getProperty("DH_HOME");		
		
		Host.exec0("rm -rf "+home+"/**");						
		File tmp=new File("/backup");
		tmp.mkdir();
		
		
		Host.exec0("cp -Af "+home+"/ /backup ");
	}
	
	public static Vector<URL> search_folder(File file) throws Exception {
		Vector<URL> vec = new Vector<URL>();
		
		if(!file.exists())
			return null;
		
		for (File tmp : file.listFiles())
			if (tmp.isFile() && tmp.getName().endsWith(".jar"))
				vec.add(tmp.toURI().toURL());
			else if (tmp.isDirectory())
				vec.addAll(search_folder(tmp));
		return vec;
	}

}